<template>

	<view class="flowLaunch-v">

		<u-toast ref="uToast"></u-toast><!-- 弹窗 -->
		<!-- <mescroll-body ref="mescrollRef" @init="mescrollInit" @down="downCallback" :sticky="true"
			:down="downOption" :up="upOption">   </mescroll-body>  -->

		<view style="background-color: white;margin: 10px;border-radius: 10px;">

			<u-form :model="form" ref="uForm">

				<!-- 	<u-form-item class="text-input" label-width="150" label="检验批号 :"><u-input type="text"
						v-model="form.code" disabled="disabled" placeholder="" /></u-form-item> -->
				<u-form-item class="text-input" label-width="150" label="物料 :"><u-input v-model="form.materia"
						disabled="disabled" placeholder="" /></u-form-item>
			<!-- 	<u-form-item class="text-input" label-width="150" label="检验规则 :"><u-input v-model="form.ruleCode"
						disabled="disabled" placeholder="" /></u-form-item> -->
				<u-form-item class="text-input" label-width="150" label="检验员 :"><u-input v-model="form.employeeName"
						disabled="disabled" placeholder="" /></u-form-item>
				<u-form-item class="text-input" label-width="150" label="开始时间 :"><u-input v-model="form.startTime"
						disabled="disabled" placeholder="" /></u-form-item>
				<u-form-item class="text-input" label-width="150" label="结束时间 :"><u-input v-model="form.endTime"
						disabled="disabled" placeholder="" /></u-form-item>
				<u-form-item class="text-input" label-width="150" label="数量 :"><u-input v-model="form.incomingQty"
						disabled="disabled" placeholder="" :disabled="form.employeeCode != userCode" /></u-form-item>
				<u-form-item class="text-input" label-width="200" label="物料附件 :">


					<shzy-file v-model="form.materialFile" showButton  disabled/>

				</u-form-item>
				<u-form-item class="text-input" label-width="200" label="检验方案附件 :">

					<shzy-file v-model="form.checkCardFile" showButton disabled/>

				</u-form-item>
				<u-form-item class="text-input" label-width="150" label="备注 :"><u-input v-model="form.remark"
						style="padding-right: 10px;" :disabled="form.employeeCode != userCode" /></u-form-item>
			</u-form>

		</view>

		<view class="flow-list" v-if="list.length > 0">
			<view class="flow-list-box">
				<uni-swipe-action ref="swipeAction">
					<uni-swipe-action-item v-for="(item, index) in list" :key="item.id" :threshold="0"
						style="margin-bottom: 10px;">
						<view class="item" @click="checkUser() == true ? goDetail(item,index):null" :id="'item'+index"
							ref="mydom">
							<view class="item-left">

								<view class="item-tag">
									<u-tag v-show="item.ReferTo=='Y'" text="参" mode="light" type="warning" />
									<u-tag v-show="item.Exempt=='Y'" style="margin-left: 10rpx;" text="免" mode="light"
										type="success" />
									<u-tag v-show="item.Destructiveness=='Y'" style="margin-left: 10rpx;" text="破"
										mode="light" type="warning" />
									<u-tag v-show="item.AutoFlag=='N'" style="margin-left: 10rpx;" text="手" mode="light"
										type="warning" />
									<u-tag v-show="item.AutoFlag=='Y'" style="margin-left: 10rpx;" text="自" mode="light"
										type="warning" />

								</view>


								<view class="title u-line-1 u-font-28">抽样方案 :

									<text class="titInner">{{item.SamplingTypeDes ? item.SamplingTypeDes : ''}}</text>
									<text class="titInner titInner-samplingQty"
										@click.stop="checkUser() == true ? SampleStatus(true,item) : null"
										style="background-color: dodgerblue; border: 1px; padding: 5px; color: white; width: 30px; height: 30px;">
										{{item.SamplingQty}}<text style="display:none;">{{item.SampleId}}</text>
									</text>

									<text class="titInner" @click="checkUser() == true ? insert('N',index) : null"
										size="30" @click.stop="checkUser() == true ? insert('N',index) : null"
										style="background-color: dodgerblue;border: 1px;padding: 5px; color:white;width:20px;height:20px;">增
									</text>
									<text v-if = "item.Type == 'ration' && item.Status == 'OK'" class="titInner" size="30"
										style="background-color: green;border: 1px;padding: 5px; color:white;width:20px;height:20px;">合格
									</text>
									<text v-else-if = "item.Type == 'ration' && item.Status == 'NG'" class="titInner" size="30"
										style="background-color: red;border: 1px;padding: 5px; color:white;width:20px;height:20px;">不合格
									</text>
								</view>

								<!-- <u-icon name="edit-pen" size="30" color="#00ff7f" style="float: left;"></u-icon> -->

								<text class="title u-line-1 u-font-28"> 检验条目 :<text
										class="titInner">{{item.InnspectionName ? item.InnspectionName : ''}}</text>
									<text
										class="titInner">{{item.InnspectionEntryName ? item.InnspectionEntryName : ''}}</text></text>

								<text class="title u-line-1 u-font-28">检验类型 :<text class="titInner">
										<template v-if="item.Type=='qualitative'">定性</template>
										<template v-else>定量</template>
									</text></text>

							</view>

						</view>
					</uni-swipe-action-item>
				</uni-swipe-action>

			</view>

		</view>


		<view class="buttom-actions" v-if="form.employeeCode == userCode">
			<u-button class="buttom-btn" @click="checkUser() == true ? insert('Y',null) : null"
				style="border-right: 2px solid lightgray;background-color:dodgerblue;color:white;">新增</u-button>
			<u-button class="buttom-btn" @click="save"
				style="border-right: 2px solid lightgray;background-color:dodgerblue;color:white;">保存</u-button>
			<u-button class="buttom-btn" @click="submit" style="background-color:dodgerblue;color:white;">提交</u-button>
		</view>


		<view>
			<u-popup v-model="popupshow" mode="center" :closeable="true" width="500" height="400" border-radius="10">
				<view style="padding-left: 10px; padding-top: 10px;font-size: 16px;">修改抽样数量</view>
				<view style="border-bottom: 1px solid lightgray;padding-top: 8px;"></view>
				<view>

					<u-form :model="dataForm" ref="dataForm" :errorType="['toast']" label-position="left"
						label-width="150" label-align="left" class="shzy-form">

						<u-form-item label="抽样数量" prop="samplingQty" label-width="135" required class="form-item"
							:border-bottom="false">
							<u-input :border="true" required v-model="dataForm.samplingQty" placeholder="请输入"
								class="form-input"></u-input>
						</u-form-item>

						<!-- 按钮 -->
						<view>
							<u-button class="buttom-btn2"
								@click="checkUser() == true ? SampleStatus(false,null) : null">
								取消
							</u-button>
							<u-button class="buttom-btn2" type="primary" @click="confirmSample">
								确定
							</u-button>
						</view>

					</u-form>
				</view>
			</u-popup>
		</view>

	</view>

</template>
<script>
	import uicon from '@/uview-ui/components/u-icon/u-icon.vue'
	import resources from '@/libs/resources.js'
	import upopup from '@/uview-ui/components/u-popup/u-popup.vue'
	// import MescrollMixin from "@/uni_modules/mescroll-uni/components/mescroll-uni/mescroll-mixins.js";
	import {
		getInspectionList,
		getInfo,
		submitinspectionlot,
		saveinspectionlot,
		SamplingQty
	} from '@/api/q1/business/inspection/inspection.js'
	export default {
		//mixins: [MescrollMixin],
		data() {
			return {
				dataForm: {
					code: "",
					sampleId: "",
					samplingQty: 0, // 抽样数量
				},
				popupshow: false,
				confirmed: '',
				checked: false,
				form: {
					sn: '',
					batch: "",
					materia: ''
				},

				flowStatus: '',
				downOption: {
					use: true,
					auto: true
				},
				upOption: {
					page: {
						num: 0,
						size: 10,
						time: null
					},
					empty: {
						use: true,
						icon: resources.message.nodata,
						tip: "暂无数据",
						fixed: true,
						top: "300rpx",
					},
					textNoMore: '没有更多数据',
				},
				keyword: '',
				list: [], // 抽样方案集合
				customColumnList: [],
				id: '',
				code: '',
				userCode: '', // 登录人code
				userName: '' // 登录人名称
				//:right-options="options"
				// options: [{
				// 	text: '删除',
				// 	style: {
				// 		backgroundColor: '#dd524d'
				// 	}
				// }],
			}
		},
		onLoad(e) {
			this.id = e.id;
			this.code = e.code;
			uni.setNavigationBarTitle({
				title: this.code
			})

		},
		onShow() {
			this.upCallback()
		},
		onUnload() {
			uni.$off('refresh')
		},
		watch: {

			'form.startTime'(value) {
				if (value == null || value == '') return;
				const date = new Date(value);
				// 将日期对象格式化为'yyyy-MM-dd HH:mm:ss'格式的字符串
				const formattedDate = date.getFullYear() +
					"-" + (date.getMonth() + 1).toString().padStart(2, "0") +
					"-" + date.getDate().toString().padStart(2, "0") +
					" " + date.getHours().toString().padStart(2, "0") +
					":" + date.getMinutes().toString().padStart(2, "0") +
					":" + date.getSeconds().toString().padStart(2, "0");
				this.form.startTime = formattedDate;
			},

			'form.endTime'(value) {
				if (value == null || value == '') return;
				const date = new Date(value);
				// 将日期对象格式化为'yyyy-MM-dd HH:mm:ss'格式的字符串
				const formattedDate = date.getFullYear() +
					"-" + (date.getMonth() + 1).toString().padStart(2, "0") +
					"-" + date.getDate().toString().padStart(2, "0") +
					" " + date.getHours().toString().padStart(2, "0") +
					":" + date.getMinutes().toString().padStart(2, "0") +
					":" + date.getSeconds().toString().padStart(2, "0");
				this.form.endTime = formattedDate;
			},
		},
		methods: {

			// 卡控:检验员需是当前登录人才可以操作
			checkUser(method, item, flag) {

				if (this.form.employeeCode != this.userCode) {

					this.$refs.uToast.show({
						title: '当前检验员不是当前登录人，当前登录人是:' + this.userName,
						type: 'default',
						duration: 1000,
					})

					return false;
				}

				return true;
			},

			// 新增抽样方案
			insert(sample, index) {

				const params = JSON.stringify({
					code: this.form.code, // 检验批号
					sample: sample, // 是否增加抽样方案
					sampleId: index != null ? this.list[index].SampleId : '', // 抽样方案id
					samplingQty: index != null ? this.list[index].SamplingQty : 0,
					receivedQty: index != null ? this.list[index].ReceivedQty : 0,
					rejectionQty: index != null ? this.list[index].RejectionQty : 0,
					incomingQty: this.form.incomingQty

				});

				uni.navigateTo({
					url: '/pages/q1/business/inspection/addSample?params=' +
						params
				})

				// if (sample == 'N') {
				// 	event.stopPropagation();
				// } // 阻止事件冒泡 this.$event.stopPropagetion(); 
			},

			// 打开或者关闭弹窗
			SampleStatus(flag, item) {

				if (flag == true) {
					const SamplingType = item.SamplingType
					if (SamplingType == '1' || SamplingType == '4') { // 根据字典项抽样方案编码来判断的
						this.$refs.uToast.show({
							title: '只有固定抽样，固定比例，执行时自行设置才可修改抽样数量',
							type: 'error',
							duration: 1000
						})
						return
					}

					// 绑定要提交的值
					this.dataForm.code = this.form.code;
					this.dataForm.sampleId = item.SampleId;
					this.dataForm.samplingQty = item.SamplingQty;
				}

				this.popupshow = flag;
			},

			// 确认数量
			confirmSample() {

				var error_msg = '';
				console.log('输入:' + this.dataForm.samplingQty + ',表单:' + this.form.incomingQty)
				error_msg = this.dataForm.samplingQty == null || this.dataForm.samplingQty == "" ?
					'请输入抽样数量' : error_msg;
				error_msg = error_msg == '' && this.dataForm.samplingQty > this.form.incomingQty ?
					'抽样数量不能大于数量' : error_msg;

				if (error_msg != '') {
					this.$refs.uToast.show({
						title: error_msg,
						type: 'error'
					})
					return;
				}

				SamplingQty(this.dataForm).then(res => {
					if (res.code == 200) {
						this.$refs.uToast.show({
							title: res.msg,
							type: 'success',
							duration: 1000,
							callback: () => {
								this.popupshow = false;
								this.upCallback();
							},
							bind: this
						})
					} else {
						this.$refs.uToast.show({
							title: res.data,
							type: 'error'
						})
					}
				})

			},

			//保存
			save() {
				saveinspectionlot(this.form).then(res => {

					// 1. 获取当前页面栈实例（此时最后一个元素为当前页）
					let pages = getCurrentPages()
					// 2. 上一页面实例				
					let prevPage = pages[pages.length - 2]
					// 3. 给上一页面实例绑定getValue()方法和参数（注意是$vm）
					prevPage.$vm.getValue("success")
					// 4. 返回上一页面
					uni.navigateBack({
						delta: 1 // 返回的页面数
					})
				})
			},

			//提交
			submit() {

				this.form.confirmed = this.confirmed
				submitinspectionlot(this.form).then(res => {

					if (res.data.confirm == 'Y') {

						// 二次确认
						this.$confirm('当前检验批已填写破坏性数量，是否已确认填写正确？', '提示', {
							type: 'warning'
						}).then(() => {
							this.confirmed = "Y";
							this.submit();
						});

					} else {
						// 1. 获取当前页面栈实例（此时最后一个元素为当前页）
						let pages = getCurrentPages()
						// 2. 上一页面实例				
						let prevPage = pages[pages.length - 2]
						// 3. 给上一页面实例绑定getValue()方法和参数（注意是$vm）
						prevPage.$vm.getValue("success")
						// 4. 返回上一页面
						uni.navigateBack({
							delta: 1 // 返回的页面数
						})
					}

				}).catch((err) => {

				})

			},

			change(e, status) {
				console.log(e);
			},

			upCallback() {

				getInspectionList(this.code).then(res => {

						let name = ''
						const list = []
						for (let i = 0; i < res.data.list.length; i++) {
							if (res.data.list[i].SamplingTypeDes) {
								name = res.data.list[i].SamplingTypeDes
							} else {
								res.data.list[i].SamplingTypeDes = name
							}
							res.data.list[i].defectStatus2 = res.data.list[i].defectStatus == 'Y'
							list.push(res.data.list[i])
						}

						this.customColumnList = res.data.customColumnList
						//console.log(list)
						this.list = list
						// 获取当前登录人与当前检验员
						this.userCode = uni.getStorageSync('employeeCode');
						this.userName = uni.getStorageSync('employeeName');

						console.log('userCode=' + this.userCode + '，employeeCode=' + this.form.employeeCode)
					}).catch(() => {
						//this.mescroll.endErr();
					}),
					getInfo(this.id).then(res => {
						this.form = res.data;
						this.form.materia = this.form.materialCode + " " + this.form.materialDes
						// this.$set(this.form, 'sn', arr[0].value)
						// this.$set(this.form, 'batch', arr[1].value)
					})
			},


			goDetail(item, index) {

				const params = JSON.stringify({
					type: item.Type, // 定量还是定性
					// 报检详情参数
					model: item,
					customColumnList: this.customColumnList,
					// 定性缺陷参数
					formData: item,
				})
				uni.navigateTo({
					url: '/pages/q1/business/inspection/writeinspection?params=' + params
				})
			},


			getLableValue(value) {
				var lableValue = ''
				switch (value) {
					case 1:
						lableValue = '正常'

						break;
					case 2:
						lableValue = '逾期'
						break;
					case 3:
						lableValue = '即将逾期'
						break;
					default:
						lableValue = '正常'
						break;
				}
				return lableValue
			}
		}
	}
</script>

<style lang="scss">
	page {
		background-color: #f0f2f6;
	}

	.edit-pen {
		font-size: 20px;
		background-color: #55aaff;
		margin-left: 5px;
	}

	.item-tag {

		position: absolute;
		right: 10px;
		top: 15px;
	}

	.flowLaunch-v {
		width: 100%;

		.text-input {
			padding-left: 20rpx;
			padding-right: 20rpx;
		}

		.flow-list {
			padding-bottom: 44px;
		}

		.flow-list-box {
			width: 95%;
			margin-top: 10px;

			.item {

				height: 110px;


			}


		}
	}

	.shzy-form {
		margin-top: 40rpx;
	}

	.form-item {

		margin-left: 30rpx;

		.form-input {
			margin-right: 20rpx;
		}
	}

	.buttom-btn2 {
		margin-top: 40rpx;
		margin-left: 30rpx;
		width: 42%;
		float: left;
	}
</style>